package com.qixin.modules.ea.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qixin.modules.ea.entity.*;
import com.qixin.modules.ea.mapper.*;
import com.qixin.modules.ea.service.IEaPhoneRecordService;
import com.qixin.modules.ea.vo.CommunicationPageVo;
import com.qixin.modules.ea.vo.PhoneRecordPageVo;
import com.qixin.modules.eaBasic.entity.EaTask;
import com.qixin.modules.eaBasic.mapper.EaTaskMapper;
import com.qixin.modules.eaBasic.util.ChangeIdToNameUtil;
import com.qixin.modules.eaBasic.util.WorkFlowUtil;
import com.qixin.modules.eaBasic.vo.EaTaskVo;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.util.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * @Description: 电话记录单
 * @Author: qixin-boot
 * @Date:   2021-07-06
 * @Version: V1.0
 */
@Service
public class EaPhoneRecordServiceImpl extends ServiceImpl<EaPhoneRecordMapper, EaPhoneRecord> implements IEaPhoneRecordService {

    @Autowired
    private EaPhoneRecordMapper eaPhoneRecordMapper;
    @Autowired
    private EaTaskMapper eaTaskMapper;
    @Value(value = "${server.fileurl}")
    private String fileurl;
    @Autowired
    private WorkFlowUtil workFlowUtil;
    @Autowired
    private ChangeIdToNameUtil changeIdToNameUtil;


    @Override
    @Transactional
    public Map<String,Object> saveMain(EaPhoneRecord eaPhoneRecord) {
        Map<String,Object> returnMap = new HashMap<String,Object>();
        Object result = FillRuleUtil.executeRule("dhjl_code", null);  //获取单据编号
        eaPhoneRecord.setBillNo(result.toString());

        String saveType = eaPhoneRecord.getSaveType();
        if(saveType.equals("add")) {  //add保存,send提交
            eaPhoneRecord.setBillStatus("0");   //单据状态:0未提交,1审批中,2已审批,3已退回
        }else{
            eaPhoneRecord.setBillStatus("1");   //单据状态:0未提交,1审批中,2已审批,3已退回
        }

        eaPhoneRecord.setId(Uuid32Util.getUUid());  //主键
        eaPhoneRecordMapper.insert(eaPhoneRecord);

        //查询电话记录单
        //新增待办
        EaTask eaTask = new EaTask();
        eaTask.setId(Uuid32Util.getUUid());
        eaTask.setFormType("11");  //单据类型:1电话记录单,2借款单,3还款单,4出差申请单,5出差申请变更单,6招待费申请单,7招待费申请变更单,8招待费报销单,9资金支付审批单,10电话记录单,11电话记录单
        eaTask.setAuditManId(eaPhoneRecord.getAuditManId());   //审批人id
        eaTask.setAuditMan(eaPhoneRecord.getAuditMan());    //审批人
        //提交类型:保存:add,提交:send
        if(saveType.equals("add")){  //add保存,send提交
            eaTask.setStatus("0");
        }else{
            eaTask.setStatus("1");
        }
        eaTask.setFormId(eaPhoneRecord.getId());    //单据id
        eaTask.setFormCode(eaPhoneRecord.getBillNo());   //单据编号
        eaTask.setMemo(eaPhoneRecord.getCause());    //备注
//        eaTask.setTotalFee(new BigDecimal(0)); //总金额
        eaTask.setSort("11");   //排序
        eaTask.setTitle("电话记录单");  //标题
        eaTask.setSendManId(eaPhoneRecord.getPersonId());    //发送人id
        eaTask.setSendMan(changeIdToNameUtil.getNameById(eaPhoneRecord.getPersonId()));    //发送人
        eaTask.setSendDepartId(eaPhoneRecord.getDeptId());  //发送人部门id
        eaTask.setSendDepart(changeIdToNameUtil.getNameByDepartId(eaPhoneRecord.getDeptId()));   //发送人部门
        eaTask.setSendTime(new Date());    //发送时间
        eaTaskMapper.insert(eaTask);

        returnMap.put("id",eaPhoneRecord.getId());
        returnMap.put("code","0");
        returnMap.put("message","保存成功!");
        return returnMap;
    }

    @Override
    @Transactional
    public Map<String,Object> updateMain(EaPhoneRecord eaPhoneRecord) {
        Map<String,Object> returnMap = new HashMap<String,Object>();

        //如果picture中有http://localhost:9092/qixin-boot/aaa.png,要处理只保留文件名
        String picture = eaPhoneRecord.getPicture() != null ? eaPhoneRecord.getPicture().toString() : "";
        // update-begin-by wujinbiao 2022/3/23 16:07 for 上传文件路径如果有包含地址直接取文件名
        eaPhoneRecord.setPicture(picture);
        String str = "";
        if (StringUtils.isNotBlank(picture) && "http".equals(picture.substring(0,4))){
            int i = picture.indexOf("fybx-boot");
            str = picture.substring(i+10,picture.length());
            eaPhoneRecord.setPicture(str);
        }
        // update-end-by wujinbiao 2022/3/23 16:07 for 上传文件路径如果有包含地址直接取文件名


        String saveType = eaPhoneRecord.getSaveType();
        if(saveType.equals("add")) {  //add保存,send提交
            EaPhoneRecord eaPhoneRecord1 = eaPhoneRecordMapper.selectById(eaPhoneRecord.getId());
            eaPhoneRecord.setBillStatus(eaPhoneRecord1.getBillStatus());   //单据状态:0未提交,1审批中,2已审批,3已退回
        }else{
            eaPhoneRecord.setBillStatus("1");   //单据状态:0未提交,1审批中,2已审批,3已退回
        }

        eaPhoneRecordMapper.updateById(eaPhoneRecord);

        //修改待办
        Map<String,Object> paramsMap4 = new HashMap<String,Object>();
        paramsMap4.put("form_id",eaPhoneRecord.getId());
        List<EaTask> eaTaskList = eaTaskMapper.selectByMap(paramsMap4);
        for (EaTask eaTask:eaTaskList) {
            eaTask.setAuditManId(eaPhoneRecord.getAuditManId());   //审批人id
            eaTask.setAuditMan(eaPhoneRecord.getAuditMan());    //审批人
            //提交类型:保存:add,提交:send
            if(saveType.equals("add")){  //add保存,send提交
                eaTask.setStatus("0");
            }else{
                eaTask.setStatus("1");
            }
            eaTask.setFormId(eaPhoneRecord.getId());    //单据id
            eaTask.setFormCode(eaPhoneRecord.getBillNo());   //单据编号
            eaTask.setMemo(eaPhoneRecord.getCause());    //备注
//            eaTask.setTotalFee(new BigDecimal(0)); //总金额
            eaTask.setSendManId(eaPhoneRecord.getPersonId());    //发送人id
            eaTask.setSendMan(changeIdToNameUtil.getNameById(eaPhoneRecord.getPersonId()));    //发送人
            eaTask.setSendDepartId(eaPhoneRecord.getDeptId());  //发送人部门id
            eaTask.setSendDepart(changeIdToNameUtil.getNameByDepartId(eaPhoneRecord.getDeptId()));   //发送人部门
            eaTask.setSendTime(new Date());    //发送时间
            eaTaskMapper.updateById(eaTask);
        }

        returnMap.put("id",eaPhoneRecord.getId());
        returnMap.put("code","0");
        returnMap.put("message","编辑成功!");
        return returnMap;
    }

    @Override
    @Transactional
    public Map<String,Object> delMain(String id) {
        Map<String,Object> retrunMap = new HashMap<String,Object>();

        //电话记录单状态为未提交时,可以删除
        EaPhoneRecord eaPhoneRecord = eaPhoneRecordMapper.selectById(id);
        String billStatus = eaPhoneRecord.getBillStatus();   //单据状态:0时可以删除,其它提示
        if(!billStatus.equals("0")){
            retrunMap.put("code","-1");
            retrunMap.put("message","电话记录单为未提交时,才能被删除!");
            return retrunMap;
        }

        //删除相应的待办
        Map<String,Object> paramaMap = new HashMap<String,Object>();
        paramaMap.put("form_id",id);
        List<EaTask> eaTaskList = eaTaskMapper.selectByMap(paramaMap);
        if(eaTaskList != null && eaTaskList.size() > 0){
            EaTask eaTask = eaTaskList.get(0);

            //删除相应的工作流
            workFlowUtil.deleteWorkFlowById(eaTask.getWorkflowTaskId(),eaTask.getProcinstId());

            eaTaskMapper.deleteById(eaTask.getId());
        }

        //删除主表数据
        eaPhoneRecordMapper.deleteById(id);

        retrunMap.put("code","0");
        retrunMap.put("message","删除成功!");
        return retrunMap;
    }

    //查询电话记录单详情
    @Override
    public Map<String,Object> selectById(String id) {
        Map<String,Object> queryWrapper = new HashMap<String,Object>();
        queryWrapper.put("id",id);  //电话记录单id
        queryWrapper.put("page",0);
        queryWrapper.put("limit",0);
        List<EaPhoneRecord> eaPhoneRecordList = eaPhoneRecordMapper.selecteaPhoneRecord(queryWrapper);
        Map<String,Object> returnMap = new HashMap<String,Object>();

        if(eaPhoneRecordList.size() > 0){
            for (EaPhoneRecord eaPhoneRecord : eaPhoneRecordList) {
                Map map = JSON.parseObject(JSON.toJSONString(eaPhoneRecord, SerializerFeature.WriteMapNullValue), Map.class);

                //格式化时间-创建时间
                Long createTime = map.get("createTime") != null ? Long.parseLong(map.get("createTime").toString()) : null;
                String createTimeStr = DateFormatUtil.formatDateyyMMddHHmmss(createTime);
                map.put("createTime",createTimeStr);

                //格式化时间-更新日期
                Long updateTime = map.get("updateTime") != null ? Long.parseLong(map.get("updateTime").toString()) : null;
                String updateTimeStr = DateFormatUtil.formatDateyyMMddHHmmss(updateTime);
                map.put("updateTime",updateTimeStr);

                //格式化时间
                Long phoneDate = map.get("phoneDate") != null ? Long.parseLong(map.get("phoneDate").toString()) : null;
                String phoneDateStr = DateFormatUtil.formatDateyyMMdd(phoneDate);
                map.put("phoneDate",phoneDateStr);

                //更新时间-用于校验时效性
                map.put("time",updateTimeStr);

                //格式化时间-单据日期
                Long billDate = map.get("billDate") != null ? Long.parseLong(map.get("billDate").toString()) : null;
                String billDateStr = DateFormatUtil.formatDateyyMMdd(billDate);
                map.put("billDate",billDateStr);

                //添加图片
                String picture = map.get("picture") != null ? map.get("picture").toString() : "";
                List<Map<String,Object>> fileList = GetUrlUtil.getUrl(picture,fileurl);

                //添加图片fileList
                map.put("fileList",fileList);

                //接电部室编码转中文
                String acceptDept = map.get("acceptDept") != null ? map.get("acceptDept").toString() : "";
                String acceptDeptName = changeIdToNameUtil.getNameByDepartId(acceptDept);
                map.put("acceptDeptName",acceptDeptName);

                returnMap = map;

            }
        }
        return returnMap;
    }

    @Override
    @Transactional
    public Map<String, Object> audit(EaTaskVo eaTaskVo) {
        Map<String,Object> returnMap = new HashMap<String,Object>();
        String id = EmptyUtil.checkNull(eaTaskVo.getId());   //单据id
//        String auditManId = EmptyUtil.checkNull(eaTaskVo.getAuditManId());   //审批人id
//        String auditMan = EmptyUtil.checkNull(eaTaskVo.getAuditMan());   //审批人
        String auditComment = EmptyUtil.checkNull(eaTaskVo.getAuditComment());   //审批意见
        String status = EmptyUtil.checkNull(eaTaskVo.getStatus());   //单据状态:2通过,3退回

        //获取电话记录单-更新状态
        EaPhoneRecord eaPhoneRecord = eaPhoneRecordMapper.selectById(id);
        eaPhoneRecord.setBillStatus(status);
        eaPhoneRecordMapper.updateById(eaPhoneRecord);

        Map<String,Object> paramsMap = new HashMap<String,Object>();
        paramsMap.put("form_id",eaPhoneRecord.getId());
        List<EaTask> eaTaskList = eaTaskMapper.selectByMap(paramsMap);
        if(eaTaskList != null && eaTaskList.size() > 0){
            EaTask eaTask = eaTaskList.get(0);
            //eaTask.setAuditManId(auditManId);
            //eaTask.setAuditMan(auditMan);
            eaTask.setAuditComment(auditComment);
            eaTask.setStatus(status);

            try {
                if(status.equals("3") || status.equals("2")){
                    eaTask.setFinishTime(new Date());   //完成时间
                }
                eaTask.setAuditTime(new Date());    //审批时间
                eaTaskMapper.updateById(eaTask);

                returnMap.put("code","0");
                returnMap.put("message","审核成功!");
                return returnMap;
            }catch (Exception e){
                returnMap.put("code","-1");
                returnMap.put("message","系统异常,审核失败!");
                return returnMap;
            }
        }else{
            returnMap.put("code","-1");
            returnMap.put("message","待办不存在!");
            return returnMap;
        }
    }

    @Override
    public EaPhoneRecord selectByApplyId(String applyId) {
        EaPhoneRecord eaPhoneRecord = eaPhoneRecordMapper.selectByApplyId(applyId);
        return eaPhoneRecord;
    }

    @Override
    public List<EaPhoneRecord> selectByMainId(String mainId) {
        return eaPhoneRecordMapper.selectByMainId(mainId);
    }

    //查询电话记录单列表
    @Override
    public Map<String, Object> list(PhoneRecordPageVo phoneRecordPageVo) {
        Map<String,Object> returnMap = new HashMap<String,Object>();
        String page = EmptyUtil.checkNull(phoneRecordPageVo.getPage());
        String limit = EmptyUtil.checkNull(phoneRecordPageVo.getLimit());
        String keyword = EmptyUtil.checkNull(phoneRecordPageVo.getKeyword());
        String userid = EmptyUtil.checkNull(phoneRecordPageVo.getUserid());   //用户id
        String status = EmptyUtil.checkNull(phoneRecordPageVo.getStatus());   //状态
        String billNo = EmptyUtil.checkNull(phoneRecordPageVo.getBillNo());   //单据编号(pc)
        String explainStr = EmptyUtil.checkNull(phoneRecordPageVo.getCasue());   //事由(pc)
        String sysOrgCode = EmptyUtil.checkNull(phoneRecordPageVo.getSysOrgCode());   //所属组织(pc)

        Map<String,Object> paramsMap = new HashMap<String,Object>();
        String keyword1 = "%" + keyword + "%";
        paramsMap.put("keyword",keyword1);
        paramsMap.put("page",(Integer.parseInt(page) -1) * Integer.parseInt(limit));
        paramsMap.put("limit",Integer.parseInt(limit));
        paramsMap.put("userid",userid);
        paramsMap.put("status",status);
        paramsMap.put("billNo",billNo);
        paramsMap.put("explainStr",explainStr);
        paramsMap.put("sysOrgCode",sysOrgCode);
        List<EaPhoneRecord> eaPhoneRecordList = eaPhoneRecordMapper.selecteaPhoneRecord(paramsMap);

        List<Map<String,Object>> mapList = new ArrayList<Map<String,Object>>();
        if(eaPhoneRecordList.size() > 0){
            for (EaPhoneRecord eaPhoneRecord : eaPhoneRecordList) {
                Map map = JSON.parseObject(JSON.toJSONString(eaPhoneRecord, SerializerFeature.WriteMapNullValue), Map.class);

                //格式化时间
                Long billDate = map.get("billDate") != null ? Long.parseLong(map.get("billDate").toString()) : null;
                String billDateStr = DateFormatUtil.formatDateyyMMdd(billDate);
                map.put("billDate",billDateStr);

                //格式化时间
                Long createTime = map.get("createTime") != null ? Long.parseLong(map.get("createTime").toString()) : null;
                String createTimeStr = DateFormatUtil.formatDateyyMMddHHmmss(createTime);
                map.put("createTime",createTimeStr);

                //格式化时间
                Long updateTime = map.get("updateTime") != null ? Long.parseLong(map.get("updateTime").toString()) : null;
                String updateTimeStr = DateFormatUtil.formatDateyyMMddHHmmss(updateTime);
                map.put("updateTime",updateTimeStr);

                //格式化时间
                Long phoneDate = map.get("phoneDate") != null ? Long.parseLong(map.get("phoneDate").toString()) : null;
                String phoneDateStr = DateFormatUtil.formatDateyyMMdd(phoneDate);
                map.put("phoneDate",phoneDateStr);

                //更新时间-用于校验时效性
                map.put("time",updateTimeStr);

                mapList.add(map);
            }
        }

        int count = 0;
        paramsMap.put("page",0);
        paramsMap.put("limit",0);
        paramsMap.put("keyword",keyword1);
        paramsMap.put("userid",userid);
        List<EaPhoneRecord> list2 = eaPhoneRecordMapper.selecteaPhoneRecord(paramsMap);
        count = list2.size();

        returnMap.put("records",mapList);
        returnMap.put("total",count);
        return returnMap;
    }

}
